﻿using System;
using System.Xml;

namespace ZYCommon
{
   

    public class DBXMLConfig
    {
        private XmlDocument myXMLDoc = new XmlDocument();
        private string strCurrentSection = "System";

        public XmlDocument GetInnerXMLDoc()
        {
            return this.myXMLDoc;
        }

        public string GetSetting(string strKey)
        {
            return this.GetSettingEx(this.strCurrentSection, strKey);
        }

        public string GetSettingEx(string strSection, string strKey)
        {
            XmlElement element = (XmlElement) this.myXMLDoc.SelectSingleNode("//setting[@sectionname='" + strSection + "' and @keyname='" + strKey + "']");
            if (element != null)
            {
                return element.InnerText;
            }
            return "";
        }

        public string GetSystemSetting(string strKey)
        {
            return this.GetSettingEx("system", strKey);
        }

        public string GetXML()
        {
            if (this.myXMLDoc.DocumentElement == null)
            {
                return null;
            }
            return this.myXMLDoc.DocumentElement.OuterXml;
        }

        public void Load(string strURL)
        {
            this.myXMLDoc.Load(strURL);
        }

        public void LoadXML(string strXML)
        {
            this.myXMLDoc.LoadXml(strXML);
        }

        public void Save(string strURL)
        {
            this.myXMLDoc.Save(strURL);
        }

        public void SaveSetting(string strKey, string strValue)
        {
            this.SaveSettingEx(this.strCurrentSection, strKey, strValue);
        }

        public void SaveSettingEx(string strSection, string strKey, string strValue)
        {
            XmlElement newChild = (XmlElement) this.myXMLDoc.SelectSingleNode("//setting[@sectionname='" + strSection + "' and @keyname='" + strKey + "']");
            if (newChild == null)
            {
                if (this.myXMLDoc.DocumentElement == null)
                {
                    this.myXMLDoc.LoadXml("<dbxmlsetting />");
                }
                newChild = this.myXMLDoc.CreateElement("setting");
                newChild.SetAttribute("sectionname", strSection);
                newChild.SetAttribute("keyname", strKey);
                this.myXMLDoc.DocumentElement.AppendChild(newChild);
            }
            newChild.InnerText = strValue;
        }

        public void SaveSystemSetting(string strKey, string strValue)
        {
            this.SaveSettingEx("system", strKey, strValue);
        }

        public string CurrentSection
        {
            get
            {
                return this.strCurrentSection;
            }
            set
            {
                this.strCurrentSection = value;
            }
        }
    }
}

